import 'package:lighthouse/index.dart';

class FunctionPage extends StatefulWidget {
  const FunctionPage({Key? key}) : super(key: key);

  @override
  State<FunctionPage> createState() => _FunctionState();
}

class _FunctionState extends State<FunctionPage> {
  bool isEdit = false;
  late UserConfigure userConfigure;

  @override
  void initState() {
    super.initState();
    // 初始化数据

    UserConfigure? userConfigure = UserConfigureCache().getCurrentData();
    if (userConfigure == null || userConfigure.homeButtonList == null) {
      userConfigure = UserConfigure()..homeButtonList = [];
    }
    this.userConfigure = userConfigure;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
            appBar: AppBar(
              title: Text(
                S.of(context).function,
              ),
              centerTitle: true,
              actions: [
                TextButton(
                    child: Text(isEdit ? "保存" : "编辑"),
                    onPressed: () async {
                      if (isEdit) {
                        bool isOK = await UserConfigureCache()
                            .updateUserConfigure(context, userConfigure);
                        if (isOK) {
                          setState(() {
                            isEdit = !isEdit;
                          });
                        }
                      } else {
                        setState(() {
                          isEdit = !isEdit;
                        });
                      }
                    }),
              ],
            ),
            body: _buildBody()),
      ),
    );
  }

  Widget _buildBody() {
    double iconRight = ((MediaQuery.of(context).size.width - 40) / 4 - 70) / 2;
    double iconTop = -5;

    List<Permission>? list =
        PermissionCache().getPermission("function")?.children;
    if (list == null) {
      return HintWidget();
    } else {
      List<Widget> slivers = [];
      if (isEdit) {
        //显示首页
        slivers.add(SliverToBoxAdapter(
          child: Container(
            height: 40,
            color: Theme.of(context).colorScheme.background,
            child: Padding(
              padding: const EdgeInsets.only(left: 17, right: 17),
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  '首页按钮',
                  style: Theme.of(context).textTheme.titleMedium,
                ),
              ),
            ),
          ),
        ));
        if (userConfigure.homeButtonList!.isNotEmpty) {
          slivers.add(
            SliverPadding(
              padding: const EdgeInsets.only(left: 17, right: 17),
              sliver: SliverGrid(
                //Grid
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4, //Grid按两列显示
                  mainAxisSpacing: 2.0,
                  crossAxisSpacing: 2.0,
                  childAspectRatio: 1.0,
                ),
                delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    Permission childPermission =
                        userConfigure.homeButtonList![index];
                    //创建子widget
                    return Stack(
                      children: [
                        Positioned.fill(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: 30,
                                height: 30,
                                child: (childPermission.imageUrl ?? "").isEmpty
                                    ? Image.asset(
                                        "images/avatar-default.png",
                                        fit: BoxFit.cover,
                                      )
                                    : Image(
                                        image: NetworkImage(
                                            childPermission.imageUrl!)),
                              ),
                              FittedBox(
                                child: Padding(
                                  padding: EdgeInsets.only(top: 5),
                                  child: Text(
                                    childPermission.name,
                                    style:
                                        Theme.of(context).textTheme.bodyMedium,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Positioned(
                          top: iconTop,
                          right: iconRight,
                          child: IconButton(
                            icon: Icon(
                              Icons.remove_circle,
                              color: Colors.red,
                            ),
                            iconSize: 20,
                            onPressed: () {
                              setState(() {
                                userConfigure.homeButtonList
                                    ?.remove(childPermission);
                              });
                            },
                          ),
                        ),
                      ],
                    );
                  },
                  childCount: userConfigure.homeButtonList!.length,
                ),
              ),
            ),
          );
        } else {
          slivers.add(
            SliverToBoxAdapter(
              child: SizedBox(
                height: 60,
                child: Center(
                  child: Text(
                    "请添加按钮",
                    style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Theme.of(context).colorScheme.onSecondary),
                  ),
                ),
              ),
            ),
          );
        }
      }

      for (Permission permission in list) {
        if (permission.children != null) {
          if (slivers.isNotEmpty) {
            slivers.add(SliverToBoxAdapter(
              child: Container(
                height: 10,
                color: Theme.of(context).colorScheme.surface,
              ),
            ));
          }
          slivers.add(SliverToBoxAdapter(
            child: Container(
              height: 40,
              color: Theme.of(context).colorScheme.background,
              child: Padding(
                padding: const EdgeInsets.only(left: 17, right: 17),
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    permission.name,
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                ),
              ),
            ),
          ));
          slivers.add(SliverPadding(
            padding: const EdgeInsets.only(left: 17, right: 17),
            sliver: SliverGrid(
              //Grid
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4, //Grid按两列显示
                mainAxisSpacing: 2.0,
                crossAxisSpacing: 2.0,
                childAspectRatio: 1.0,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  Permission childPermission = permission.children![index];

                  List<Widget> children = [
                    Positioned.fill(
                      child: TextButton(
                        onPressed: () {
                          if (!isEdit) {
                            Debug.info("path：${childPermission.path}");
                            Navigator.of(context)
                                .pushNamed(childPermission.path!);
                          }
                        },
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SizedBox(
                              width: 30,
                              height: 30,
                              child: (childPermission.imageUrl ?? "").isEmpty
                                  ? Image.asset(
                                      "images/avatar-default.png",
                                      fit: BoxFit.cover,
                                    )
                                  : Image(
                                      image: NetworkImage(
                                          childPermission.imageUrl!)),
                            ),
                            FittedBox(
                              child: Padding(
                                padding: EdgeInsets.only(top: 5),
                                child: Text(
                                  childPermission.name,
                                  style: Theme.of(context).textTheme.bodyMedium,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ];

                  if (isEdit &&
                      PermissionCache.getPermissionFromId(childPermission.id,
                              userConfigure.homeButtonList!) ==
                          null) {
                    children.add(Positioned(
                      top: iconTop,
                      right: iconRight,
                      child: IconButton(
                        icon: Icon(
                          Icons.add_circle,
                          color: Colors.blue,
                        ),
                        iconSize: 20,
                        onPressed: () {
                          setState(() {
                            Permission permission = Permission()
                              ..id = childPermission.id
                              ..name = childPermission.name
                              ..path = childPermission.path
                              ..imageUrl = childPermission.imageUrl;
                            userConfigure.homeButtonList?.add(permission);
                          });
                        },
                      ),
                    ));
                  }
                  //创建子widget
                  return Stack(
                    children: children,
                  );
                },
                childCount: permission.children!.length,
              ),
            ),
          ));
        }
      }
      if (slivers.isEmpty) {
        return HintWidget();
      }

      return CustomScrollView(
        slivers: slivers,
      );
    }
  }
}
